import { NestFactory } from '@nestjs/core'; //用來建立Nest应用的工厂
import { AppModule } from './app.module';
import { VersioningType, ValidationPipe } from '@nestjs/common';
// import { Request, Response, NextFunction } from 'express';
import { Response } from './common/response';
// import { HttpFilter } from './common/filter';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as session from 'express-session';
import { join } from 'path';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
// import { RoleGuard } from './guard/role/role.guard';
/**
 * 主函数，用于启动应用程序
 * @async 异步函数
 * @function bootstrap 启动函数
 * /
 * @returns {Promise<void>} 返回一个 Promise 对象，表示异步操作的完成
 */
// const whiteList = ['/user'];
//全局中间件
// function Middleware() {
//   return (req: Request, res: Response, next: NextFunction) => {
//     if (whiteList.includes(req.originalUrl)) next();
//     else {
//       res.send({
//         message: '请登录',
//       });
//     }
//   };
// }

async function bootstrap() {
  // 调用 NestFactory 的 create 方法，传入 AppModule 类，创建一个 Nest 应用实例
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    cors: true,
  });
  const options = new DocumentBuilder()
    .addBearerAuth()
    .setTitle('nest-demo')
    .setDescription('nest-demo')
    .setVersion('1.0')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('/api-docs', app, document);
  // app.use(Middleware());
  app.useStaticAssets(join(__dirname, 'images'));
  app.enableVersioning({
    type: VersioningType.URI,
  });
  app.use(
    session({
      secret: 'my-secret', //加密字符串
      resave: false,
      name: 'hh.sid',
      saveUninitialized: false,
      rolling: true, //每次请求都重新设置cookie,
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 7, //cookie有效时间
      },
    }),
  );
  app.useGlobalPipes(new ValidationPipe());

  // app.useGlobalFilters(new HttpFilter()); //全局异常拦截器
  app.useGlobalInterceptors(new Response()); //全局响应拦截器
  // app.useGlobalGuards(new RoleGuard()); //全局守卫
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
